package sort.seniorSort;

import sort.template;

import java.util.Arrays;

import static sort.SortCompare.getArray;

public class MergeWithInsection extends template {
    private static Comparable[] aux;

    public static void sort(Comparable[] a) {
        int N = a.length;
        aux = new Comparable[N];
        sort(a, 0, N - 1);
    }

    public static void sort(Comparable[] a, int lo, int hi) {
        if (lo >= hi) return;
        if (hi - lo < 15) {
            int mid = (lo + hi) / 2;
            sort(a, lo, mid);
            sort(a, mid + 1, hi);
            merge(a, lo, mid, hi);
        } else {
//            插入排序
            for (int i = lo + 1; i <= hi; i++) {
                for (int j = i; j > lo && less(a[j], a[j - 1]); j--) {
                    exch(a, j, j - 1);
                }
            }
        }

    }

    private static void merge(Comparable[] a, int lo, int mid, int hi) {
        int i = lo;
        int j = mid + 1;
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }
        for (int k = lo; k <= hi; k++) {
            if (i > mid) a[k] = aux[j++];
            else if (j > hi) a[k] = aux[i++];
            else if (less(aux[i], aux[j])) a[k] = aux[i++];
            else a[k] = aux[j++];
        }
    }

    public static void main(String[] args) {
        Comparable[] array = getArray(100);
        System.out.println("原来的数组:" + Arrays.asList(array));
        sort(array);
        System.out.println("排序之后的数组为:" + Arrays.asList(array));
        System.out.println(isSorted(array));
    }
}
